<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Import an Excel file.
 *
 * Simple API function that will load an Excel file from $path and parse it
 * as a multidimensional array.
 *
 * @param string $path
 *    The path to the Excel file. Must be readable.
 * @param boolean $keyed_by_headers = TRUE
 *    If TRUE, will key the row array with the header values and will
 *    skip the header row. If FALSE, will contain the headers in the first
 *    row and the rows will be keyed numerically.
 * @param boolean $keyed_by_worksheet = FALSE
 *    If TRUE, will key the data array with the worksheet names. Otherwise, it
 *    will use a numerical key.
 * @param array $custom_calls = NULL
 *    An associative array of methods and arguments to call on the PHPExcel
 *    Reader object. For example, if you wish to load only a specific worksheet
 *    to save time, you could use:
 *    @code
 *    phpexcel_import('path/to/file.xls', TRUE, TRUE, array(
 *      'setLoadSheetsOnly' => array('My sheet'),
 *    ));
 *    @endcode
 * @return array|int
 *    The parsed data as an array on success, PHPEXCEL_ERROR_LIBRARY_NOT_FOUND
 *    or PHPEXCEL_ERROR_FILE_NOT_READABLE on error.
 *
 * @see hook_phpexcel_import()
 *
 * @ingroup phpexcel_api
 */
if(!function_exists('phpexcel_import')){

  define('PHPEXCEL_ERROR_NO_HEADERS', 0);
  define('PHPEXCEL_ERROR_NO_DATA', 1);
  define('PHPEXCEL_ERROR_PATH_NOT_WRITABLE', 2);
  define('PHPEXCEL_ERROR_LIBRARY_NOT_FOUND', 3);
  define('PHPEXCEL_ERROR_FILE_NOT_WRITTEN', 4);
  define('PHPEXCEL_ERROR_FILE_NOT_READABLE', 5);
  define('PHPEXCEL_CACHING_METHOD_UNAVAILABLE', 6);
  define('PHPEXCEL_SUCCESS', 10);


  function phpexcel_import($path, $keyed_by_headers = TRUE, $keyed_by_worksheet = FALSE, $custom_calls = array()) {
    if (is_readable($path)) {
      $CI = & get_instance();
      if(!file_exists(APPPATH.'libraries/PHPExcel.php')){
        return PHPEXCEL_ERROR_LIBRARY_NOT_FOUND;
      }
      include_once(APPPATH.'libraries/PHPExcel.php');
      include_once(APPPATH.'libraries/PHPExcel/IOFactory.php');

      $cache_method = PHPExcel_CachedObjectStorageFactory::cache_in_memory;
      $cache_settings = array();

      // Is it available ? If not, return an error.
      if (empty($cache_method)) {
        return PHPEXCEL_CACHING_METHOD_UNAVAILABLE;
      }

      PHPExcel_Settings::setCacheStorageMethod($cache_method, $cache_settings);
      $xls_reader = IOFactory::createReaderForFile($path);
      $custom_calls = array(
        'setReadDataOnly' => array(TRUE),
      ) + $custom_calls;

      if (!empty($custom_calls)) {
        foreach ($custom_calls as $method => $args) {
          if (method_exists($xls_reader, $method)) {
            call_user_func_array(array($xls_reader, $method), $args);
          }
        }
      }
      $xls_data = $xls_reader->load($path);
      $data = array();
      $headers = array();
      $options = array(
        'path' => $path,
        'keyed_by_headers' => $keyed_by_headers,
        'keyed_by_worksheet' => $keyed_by_worksheet,
        'custom_calls' => $custom_calls,
      );
      $i = 0;

      foreach ($xls_data->getWorksheetIterator() as $worksheet) {
        $j = 0;

        foreach ($worksheet->getRowIterator() as $row) {
          if ($keyed_by_worksheet) {
            $i = $worksheet->getTitle();
          }
          $k = 0;

          $cells = $row->getCellIterator();

          $cells->setIterateOnlyExistingCells(FALSE);

          foreach ($cells as $cell) {
            $value = $cell->getValue();
            $value = strlen($value) ? trim($value) : '';

            if (!$j && $keyed_by_headers) {
              $value = strlen($value) ? $value : $k;
              $headers[$i][] = $value;
            }
            elseif ($keyed_by_headers) {
              $data[$i][$j - 1][$headers[$i][$k]] = $value;
            }
            else {
              $col_index = $k;
              if ($cells->getIterateOnlyExistingCells()) {
                $col_index = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1;
              }
              $data[$i][$j][$col_index] = $value;
            }

            $k++;
          }

          $j++;
        }

        if (!$keyed_by_worksheet) {
          $i++;
        }
      }
      // Free up memory.
      $xls_data->disconnectWorksheets();
      unset($xls_data);
      return $data;
    }
    else {
      return PHPEXCEL_ERROR_FILE_NOT_READABLE;
    }
  }
}